#include "dac.h"

static struct dac_dev_t dac_device;
static struct dac_factor_t dac_fac_dev;
static uint16_t dac_val=0;
void dac_set_val_out(struct dac_dev_t*dev)
{

   if(dev->factor->k_val<=1)dev->factor->k_val = 1;
   if(dev->factor->u_vout<=1)dev->factor->u_vout = 1;
   if(dev->y_setting==0)//说明上位机没有设定
   {
		 // 电压不准的问题，这里把已经计算好的份数再次计算了一次
       dac_val = (dev->factor->v_default);//*dev->factor->k_val)/(10*dev->factor->u_vout);
   }
   else{
       dac_val = (dev->y_setting);//*dev->factor->k_val)/(dev->factor->u_vout*10);
   }
   if(dac_val<=1)dac_val = 1;
   if(dac_val>=4095)dac_val = 4095;
   dev->set_register_val(dac_val);

}
uint16_t dac_get_setting_val (struct dac_dev_t *dev)
{
    return dev->y_setting;
}
void dac_change_setting_val(struct dac_dev_t*dev,uint16_t val)
{
    dev->y_setting = val;
}
/**
 * @ 根据电压值返回对应的dac 值
*/
uint16_t dac_get_vol_val(struct dac_dev_t*dev,uint16_t vol)
{
     //float val = vol/10;
     return ((dev->factor->k_val)*vol)/(10*(dev->factor->u_vout));
}

int dac_init(struct dac_dev_t **dev)
{
    dac_hal_init();
    dac_fac_dev.k_val=10;
    dac_fac_dev.u_vout=10;
    dac_fac_dev.v_default =200;//2v
    dac_device.factor = &dac_fac_dev;
    dac_device.set_register_val = dac_hal_set_value;
    dac_device.set_out=dac_set_val_out;
    dac_device.change_setting_val=dac_change_setting_val;
    dac_device.get_setting_val= dac_get_setting_val;
    dac_device.get_vol_val =dac_get_vol_val;
    *dev = &dac_device;
    return 0;
}


